/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package apteka;

import apteka.tables.Basket;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import apteka.tables.User;
import java.util.Calendar;

/**
 *
 * @author Marek
 */

@Controller
@RequestMapping("/register.htm")
public class UserRegisterController {

    @Autowired
        UserRegisterValidator userRegisterValidator;
    @Autowired
        UserManager user_man;
    @Autowired
        MailManager mailService;

    @RequestMapping(method = RequestMethod.GET)
    public String showPage(Map model) {
        User user = new User();
        model.put("user", user);
        return "register";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String process(User user, BindingResult result,Map model) {
        userRegisterValidator.validate(user, result);
        if (result.hasErrors()) {
            user.setPassword("");
            model.put("user", user);
            return "register";
        }
        user.setActivatecode(user_man.generateToken());
        user.setActive(false);
        Basket basket = new Basket();
        Calendar calen = Calendar.getInstance();
        basket.setLastchange(calen.getTime());
        user.setRegisterdate(calen.getTime());
        user.setBasket(basket);
        user_man.registerUser(user);
        mailService.SendRegisterToken(user.getEmail(), user.getActivatecode());
        model.put("username", user.getUsername());
        model.put("email",user.getEmail());
        return "registerResult";
    }

}
